import * as fs from 'fs';
import * as path from 'path';


export function readJsonFile(filePath: string): Promise<any> {
  const data = fs.readFileSync(filePath, 'utf-8');
  const jsonData = JSON.parse(data);
  return jsonData;
}

/**
 * 读取目录下所有JSON文件，不包含子目录
 * @param dirPath 目录路径
 * @returns 包含所有JSON文件内容的数组
 */
export async function readAllJsonFiles(dirPath: string): Promise<{ fileName: string, content: any }[]> {
  return new Promise((resolve, reject) => {
    fs.readdir(dirPath, (err, files) => {
      if (err) {
        reject(err);
        return;
      }
      
      const jsonFiles = files.filter(file =>
        file.endsWith('.json') &&
        fs.statSync(path.join(dirPath, file)).isFile()
      );
      
      const results: { fileName: string, content: any }[] = [];
      let processed = 0;
      
      if (jsonFiles.length === 0) {
        resolve(results);
        return;
      }
      
      jsonFiles.forEach(file => {
        const filePath = path.join(dirPath, file);
        fs.readFile(filePath, 'utf-8', (err, data) => {
          if (err) {
            console.error(`读取文件 ${file} 失败:`, err);
          } else {
            try {
              results.push({
                fileName: file,
                content: JSON.parse(data)
              });
            } catch (parseErr) {
              console.error(`解析JSON文件 ${file} 失败:`, parseErr);
            }
          }

          processed++;
          if (processed === jsonFiles.length) {
            resolve(results);
          }
        });
      });
    });
  });
}